<!-- 对 手风琴 组件的编辑 -->
<template>
  <div class="images-edit" v-if="dialogShow" style="width:960px;">
    <SetDesignDialog :title="name" :dialogVisible="dialogShow" :close="close" :saveclose="saveclose" ref="settingComponentDialog">
      <div class="edit-container-u">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="设置" name="1">
            <el-row>
              <el-col :span="12">
                <el-form :label-width="formLabelWidth" onkeypress="return event.keyCode != 13;" @submit.native.prevent>
                  <el-form-item label="展开图宽度" style="margin-bottom:0px;">
                    <el-input size="mini" v-model="data.config.pcwd" style="width: 100px;" @blur="pcwdblur"></el-input>
                    <span class="tip-color1"> 例如：60%、500</span>
                  </el-form-item>
                </el-form>
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="切换效果" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.pcisclickopen" placeholder="请选择">
                      <el-option label="滑动" :value="0"></el-option>
                      <el-option label="点击" :value="1"></el-option>
                    </el-select>
                    <span v-if="parseInt(data.config.pcisclickopen) === 1" class="tip-color1"> 设置的图片链接失效</span>
                  </el-form-item>
                </el-form>
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="切换速度" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.pcspeed" placeholder="请选择">
                      <el-option label="300" :value="300"></el-option>
                      <el-option label="400" :value="400"></el-option>
                      <el-option label="500" :value="500"></el-option>
                      <el-option label="600" :value="600"></el-option>
                      <el-option label="700" :value="700"></el-option>
                      <el-option label="800" :value="800"></el-option>
                      <el-option label="900" :value="900"></el-option>
                      <el-option label="1000" :value="1000"></el-option>
                      <el-option label="1200" :value="1200"></el-option>
                      <el-option label="1400" :value="1400"></el-option>
                      <el-option label="1600" :value="1600"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="默认展开" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.pcisopen" placeholder="请选择">
                      <el-option label="否" :value="0"></el-option>
                      <el-option label="是" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <el-form :label-width="formLabelWidth">
                  <el-form-item label="懒加载" style="margin-bottom:0px;">
                    <el-select style="width: 100px;" size="mini" v-model="data.config.islazyload" placeholder="请选择">
                      <el-option label="关闭" :value="0"></el-option>
                      <el-option label="开启" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="图片列表" name="2">
            <div class="imgList-u">
              <draggable v-model="data.dataList" class="imaged-placeholder" v-bind="{draggable:'.img-item-draggable'}" @end="datadragEnd">
                <div class="img-item img-item-draggable" v-for="(item, index) in data.dataList" :key="index">
                  <div class="image">
                    <el-image :fit="'scale-down'" :src="item.imgsrc"></el-image>
                  </div>
                  <span class="demonstration"><i @click.stop="editorLink(index)" class="el-icon-link"></i><i
                      @click.stop="editorAttr(index)" class="el-icon-edit"></i><i @click.stop="deleteImage(index)"
                      class="el-icon-delete"></i></span>
                </div>
                <div class="img-item" @click.stop="addImage" slot="header">
                  <div class="image" style="cursor:pointer;">
                    <el-image :src="ImagesPopAdd"></el-image>
                  </div>
                </div>
              </draggable>
            </div>
          </el-tab-pane>
          <el-tab-pane label="样式选择" name="3">
            <el-form :label-width="'80px'">
              <el-form-item label="当前样式" style="margin-bottom:0px;">
                <el-input size="mini" style="width:200px;" :disabled="true" v-model="data.theme">
                </el-input>
                <!-- <el-select :disabled="true" size="mini" v-model="data.theme" placeholder="请选择">
                  <el-option v-for="(item, index) in themes" :key="index" :label="item.content"
                    :value="''+item.theme">
                  </el-option>
                </el-select> -->
              </el-form-item>
            </el-form>
            <div class="iframe" v-loading="iframeLoading">
              <iframe :src="iframeSrc" frameborder="0" style="width:960px;height:400px; height:calc(100vh - 300px);" ref="iframeRender"></iframe>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </SetDesignDialog>

    <ChooseRepertory ref="chooseImage" />
    <WDialogLink ref="wDialogLink" />
    <WDialogImageAttrAndIcon ref="wDialogImageAttrAndIcon" />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import WDialogLink from '@/components/common/design/dialog/widgets/WDialogLink.vue'
import WDialogImageAttrAndIcon from '@/components/common/design/dialog/widgets/WDialogImageAttrAndIcon.vue'

import ChooseRepertory from '@/components/common/repertory/ChooseRepertory.vue'

import ImagesAccor1 from '@/assets/images/example/accor1.jpg'
import ImagesAccor2 from '@/assets/images/example/accor2.jpg'
import ImagesAccor3 from '@/assets/images/example/accor3.jpg'
import ImagesAccor4 from '@/assets/images/example/accor4.jpg'
import ImagesAccor5 from '@/assets/images/example/accor5.jpg'
import ImagesIconLink1 from '@/assets/images/example/icon_link1.png'

import ImagesPopAdd from '@/assets/images/pop_add.png'
import PaddingTop from '@/components/common/design/dialog/component/formitem/PaddingTop.vue'
import PaddingBottom from '@/components/common/design/dialog/component/formitem/PaddingBottom.vue'
import SetDesignDialog from '@/components/common/dialog/SetDesignDialog.vue'
import * as WindowType from '@/config/windowtype.js'
// import * as PubsubType from '@/config/pubsubtype.js'
import * as functions from '@/core/functions.js'
import VueFunctions from '@/core/VueFunctions.js'
import BackendjsFunctions from '@/core/BackendjsFunctions.js'
import { mapState } from 'vuex'
// import PubSub from 'pubsub-js'
import crypto from '@/core/crypto.js'
import qs from 'qs'
import _ from 'lodash'

export default {
  computed: {
    ...mapState([
      'design'
    ]),
    dataListLength () {
      return '图片数量：' + this.data.dataList.length
    }
  },
  created () {
    VueFunctions.method(WindowType.EDIT_COMPONENT_WITH_COMPONENTACCORDION, (bjComponent) => {
      this.close()
      this.dialogShow = true
      this.bjComponent = bjComponent
      this.data = bjComponent.render.data
      this.data.theme = '' + this.data.theme

      this.repertoryData = bjComponent._other.imageList

      this.activeName = '1'
      this.init = true
    })
  },
  mounted () {
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_CLOSE, (event, data) => {
    //   this.close()
    // })
    // PubSub.subscribe(PubsubType.PUBSUB_DIGLOG_COMPONENT_AND_CONTAINER_CLOSE, (event, data) => {
    //   this.close()
    // })
  },
  data () {
    return {
      dialogShow: false,
      iframeLoading: true,
      iframeStyle: {},
      formLabelWidth: '120px',
      name: '手风琴',
      bjComponent: null,
      data: null,
      iframeSrc: null,
      themes: themes,
      repertoryData: [],
      activeName: '1',
      // 是否第一次进来
      init: true,
      // 是否第一次加载样式选择
      initiframe: true,

      // import 引入
      ImagesPopAdd: ImagesPopAdd,
      // 图片列表的总数
      total: 12
    }
  },
  methods: {
    // 标签切换触发
    handleClick (tab, event) {
      if (tab.name === '3' && this.initiframe) {
        this.initiframe = false
        this.iframeLoading = true
        this.iframeStyle = {
          width: 825,
          row: 7,
          col: 1,
          compname: 'component_accordion',
          theme: this.$store.state.site.config.theme,
          color: this.$store.state.site.config.color,
          ttextalign: 'center',
          tcolor: '#888',
          now: new Date().getTime()
        }
        this.iframeStyle.token = crypto.en(JSON.stringify(this.iframeStyle))
        let query = qs.stringify(this.iframeStyle)
        this.iframeSrc = '/api/udin/component?' + query

        this.$nextTick(() => {
          this.$refs['settingComponentDialog'].open()
        })

        // iframe 加载完成后回调的方法，
        let funcname = WindowType.API_UDIN_COMPONENT_ONLOAD_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
        window[funcname] = () => {
          this.iframeLoading = false
          let componentName = this.getComponentName()
          let defaultData = BackendjsFunctions.componentDefaultData(componentName)
          let objArray = []
          for (let i = 1; i <= 7; i++) {
            defaultData.ele = '#render-' + i
            defaultData.data.theme = '' + i
            defaultData.data.dataList = defauleDataList
            objArray.push({
              renderData: _.cloneDeep(defaultData),
              title: '编号：' + i,
              theme: i
            })
            // objArray.push(_.cloneDeep(defaultData))
          }
          // 调用 iframe 中的 render 方法进行渲染
          this.$refs['iframeRender'].contentWindow.render(objArray, this.data.theme)
        }

        // 选择theme后回调的方法，并且传入选择的数据
        let funcallbackname = WindowType.API_UDIN_COMPONENT_ONLOAD_CALLBACK_.replace('[ComponentName]', this.iframeStyle.compname).toUpperCase()
        window[funcallbackname] = (renderData) => {
          this.data.theme = '' + renderData.data.theme
          if (this.init) {
            this.init = false
          }
          // 校验现在的theme是否与iframe显示的选择的theme一致
          this.$refs['iframeRender'].contentWindow.checkTheme(this.data.theme)
        }
      }
    },
    deleteImage (index) {
      let item = this.data.dataList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }

      this.data.dataList.splice(index, 1)
      this.repertoryData.splice(index, 1)
    },
    // 拖拉排序
    datadragEnd (event) {
      let item = this.repertoryData[event.oldIndex - 1]
      this.repertoryData.splice(event.oldIndex - 1, 1)
      this.repertoryData.splice(event.newIndex - 1, 0, item)
    },
    // 编辑图片属性
    editorAttr (index) {
      let item = this.data.dataList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }
      let iconNew = {}
      if (repertory.icon && JSON.stringify(repertory.icon) !== '{}') {
        iconNew.repertory = repertory.icon ? repertory.icon : null
      }
      let param = {
        imgalt: item.imgalt,
        imgtitle: item.imgtitle,
        title: item.title,
        info: item.info,
        icon: repertory.icon && JSON.stringify(repertory.icon) !== '{}' ? iconNew : null,
        iconalt: item.iconalt,
        icontitle: item.icontitle
      }

      this.$refs['wDialogImageAttrAndIcon'].open(param, (image) => {
        this.data.dataList[index].imgalt = image.imgalt
        this.data.dataList[index].imgtitle = image.imgtitle
        this.data.dataList[index].title = image.title
        this.data.dataList[index].info = image.info
        this.data.dataList[index].iconsrc = image.icon && image.icon.repertory ? functions.getRepertoryImageSrcByHostRepertory(image.icon.repertory) : ''
        this.data.dataList[index].iconalt = image.iconalt
        this.data.dataList[index].icontitle = image.icontitle
        this.repertoryData[index].icon = image.icon && image.icon.repertory ? image.icon.repertory : {}
      })
    },
    // 编辑图片的链接
    editorLink (index) {
      let item = this.data.dataList[index]
      if (!item) {
        return
      }
      let repertory = this.repertoryData[index]
      if (!repertory) {
        return
      }

      this.$refs['wDialogLink'].open({
        href: item.linkhref,
        target: item.linktarget
      }, (link) => {
        this.data.dataList[index].linkhref = link.href
        this.data.dataList[index].linktarget = link.target
      })
    },
    // 添加图片
    addImage () {
      if (this.data.dataList.length >= this.total) {
        this.$message.error('图片列表总数不能超过' + this.total + '张！')
        return
      }
      this.$refs['chooseImage'].show({ title: '选择图片', max: this.total - this.data.dataList.length, where: { type: [0, 4] }, fixedCondition: { type: true } }, (repertoryList) => {
        if (repertoryList.length > 0) {
          // let maxOrderNum = 0
          // if (this.repertoryData && this.repertoryData.length > 0) {
          //   this.repertoryData.forEach(element => {
          //     if (element.orderNum > maxOrderNum) {
          //       maxOrderNum = element.orderNum
          //     }
          //   })
          // }

          repertoryList.forEach(item => {
            // let repertoryImageSrc = { hostId: this.$store.state.host.id, repertoryId: item.id, suffix: item.suffix, type: item.type, link: item.link }
            // let src = functions.getRepertoryImageSrc(repertoryImageSrc)
            let src = functions.getRepertoryImageSrcByHostRepertory(item)

            // let repertoryData = {
            //   id: -1,
            //   parentId: 0,
            //   type: 11,
            //   orderNum: ++maxOrderNum,
            //   config: {
            //     imgsrc: '',
            //     imgtitle: '',
            //     imgalt: '',
            //     iconsrc: '',
            //     icontitle: '',
            //     iconalt: '',
            //     title: '',
            //     info: '',
            //     linkhref: '',
            //     linktarget: ''
            //   },
            //   repertory: item,
            //   child: null
            // }

            // this.repertoryData.push(repertoryData)

            this.data.dataList.push({
              imgsrc: src,
              imgtitle: '',
              imgalt: '',
              iconsrc: '',
              icontitle: '',
              iconalt: '',
              title: '',
              info: '',
              linkhref: '',
              linktarget: ''
            })
            let imghrepertory = {
              img: {},
              icon: {}
            }
            imghrepertory.img = item
            this.repertoryData.push(imghrepertory)
          })
        }
      })
    },
    getComponentName () {
      var compname = this.iframeStyle.compname
      var temp = this.titleCase(compname.replace('_', ' ')).replace(' ', '')
      return temp.replace(temp[0], temp[0].toLowerCase())
    },
    titleCase (str) {
      return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
    },
    pcwdblur (e) {
      let val = e.target.value
      if (isNaN(parseInt(val)) || parseInt(val) < 1) {
        this.data.config.pcwd = '60%'
      } else {
        let suff = val.substr(val.length - 1)
        if (suff === '%') {
          this.data.config.pcwd = parseInt(val) + '%'
        } else {
          this.data.config.pcwd = parseInt(val)
        }
      }
    },
    // ......
    close () {
      this.dialogShow = false
      this.iframeLoading = true
      this.iframeStyle = {}
      this.bjComponent = null
      this.data = null
      this.iframeSrc = ''
      this.repertoryData = []
      this.activeName = '1'
      this.init = true
      this.initiframe = true
    },
    saveclose () {
      this.bjComponent.render.data = _.cloneDeep(this.data)
      this.bjComponent._other.imageList = _.cloneDeep(this.repertoryData)
      BackendjsFunctions.saveComponent(this.bjComponent)
      this.close()
    }
  },
  components: {
    SetDesignDialog,
    PaddingTop,
    PaddingBottom,
    ChooseRepertory,
    WDialogLink,
    WDialogImageAttrAndIcon,
    draggable
  }
}

const themes = [
  { theme: '1', content: '' },
  { theme: '2', content: '' },
  { theme: '3', content: '' },
  { theme: '4', content: '' },
  { theme: '5', content: '' },
  { theme: '6', content: '' },
  { theme: '7', content: '' }
]

const defauleDataList = [
  {
    imgsrc: ImagesAccor1,
    imgtitle: '',
    imgalt: '',
    iconsrc: ImagesIconLink1,
    icontitle: '',
    iconalt: '',
    title: '手风琴标题1',
    info: '手风琴内容1，通过选择不同的显示样式配合页面的结构，使得页面页面看起来得体、美观！',
    linkhref: '',
    linktarget: ''
  },
  {
    imgsrc: ImagesAccor2,
    imgtitle: '',
    imgalt: '',
    iconsrc: ImagesIconLink1,
    icontitle: '',
    iconalt: '',
    title: '手风琴标题2',
    info: '手风琴内容2，通过选择不同的显示样式配合页面的结构，使得页面页面看起来得体、美观！',
    linkhref: '',
    linktarget: ''
  },
  {
    imgsrc: ImagesAccor3,
    imgtitle: '',
    imgalt: '',
    iconsrc: ImagesIconLink1,
    icontitle: '',
    iconalt: '',
    title: '手风琴标题3',
    info: '手风琴内容3，通过选择不同的显示样式配合页面的结构，使得页面页面看起来得体、美观！',
    linkhref: '',
    linktarget: ''
  },
  {
    imgsrc: ImagesAccor4,
    imgtitle: '',
    imgalt: '',
    iconsrc: ImagesIconLink1,
    icontitle: '',
    iconalt: '',
    title: '手风琴标题4',
    info: '手风琴内容4，通过选择不同的显示样式配合页面的结构，使得页面页面看起来得体、美观！',
    linkhref: '',
    linktarget: ''
  },
  {
    imgsrc: ImagesAccor5,
    imgtitle: '',
    imgalt: '',
    iconsrc: ImagesIconLink1,
    icontitle: '',
    iconalt: '',
    title: '手风琴标题5',
    info: '手风琴内容5，通过选择不同的显示样式配合页面的结构，使得页面页面看起来得体、美观！',
    linkhref: '',
    linktarget: ''
  }
]

</script>

<style scoped>
.edit-container-u {
  width: 840px;
  min-height: 410px;
  min-height:calc(100vh - 200px);
}
.images-edit .image-slot {
  color: #656565;
  display: flex;
  justify-content: center;
  align-items: center;
}
.imgList-u {
  height:calc(100vh - 260px);
  overflow-y: auto;
}
</style>
